<?php

namespace App\Http\Middleware;

use Closure;
// use Illuminate\Http\Request;
use App\Http\Requests\MenuRequest;
use App\Models\BackstageModel;
use App\Models\CommonModel;
class BackstageMiddleware
{
    public $uid = 0;

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    // public function __construct()
    // {
        
    // }
    public function handle($request, Closure $next)
    {
        $action = \Route::currentRouteAction();
        list($controller, $method) = explode('@', $action);
        $controller = substr(strrchr($controller,'\\'),1);
        $class = str_replace("controller",'',strtolower($controller));
        $uri = $class.'/'.$method;
        // $uri = $request->getRequestUri();
        // dd($uri);
        if($class!='login' && $method != 'login' && $method != 'code' && $method != 'userLogin' && $method != 'getMenu' && $method != 'error' && $method != 'info'){
            if(empty(session('admin'))){
                // return redirect('backstage/login');
                echo '<script>top.location.href="http://'.$_SERVER['HTTP_HOST'].'/backstage/login";</script>';
            }else{
                // return redirect('backstage/index');
                // dd($uri);
                if($uri!='index/index'){
                    $info = CommonModel::getOne('admin_group',['id'=>session('admin')->id]);
                    // 权限控制
                    if(!empty($info->authority)){
                        $permission=unserialize($info->authority);
                    }
                    // dd($class);
                    if($request->isMethod('get')){
                        if(empty($permission[$class])){
                            $error = ['status'=>-1,'message'=>'没有权限！'];
                            return response()->view('backstage/public/message', ['error'=>$error]);
                        }else{
                            if(!in_array($method,$permission[$class])){
                                $error = ['status'=>-1,'message'=>'对不起，权限不足！'];
                                return response()->view('backstage/public/message', ['error'=>$error]);
                            }
                        }
                    }elseif($request->isMethod('post')){
                        if(!in_array($method,$permission[$class])){
                            $error = ['status'=>-1,'message'=>'对不起，权限不足！'];
                            return response()->json($error);
                        }
                    }
                }
                
                
            }
        }
        // dd($request);
        return $next($request);
    }



}
